"use client";

import * as React from "react";
import { format } from "date-fns";
import { Calendar as CalendarIcon } from "lucide-react";

import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Calendar } from "@/components/ui/calendar";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";

function DatePickerWithRange({ className,
  initStartDate, initEndDate,
  setStartDate, setEndDate }) {
  const [date, setDate] = React.useState({
    from: initStartDate,
    to: initEndDate,
  });

  const setDateHook = (range) => {
    setStartDate(range.from);
    setEndDate(range.to);
    setDate(range);
  };

  return (
    <div className={cn("grid gap-2", className)}>
    <Input className="hidden" name="start_date" value={date.from} defaultValue={new Date()} />
    <Input className="hidden" name="end_date" value={date.to} defaultValue={new Date()} />
      <Popover>
        <PopoverTrigger asChild>

            <Button
              id="date"
              variant={"outline"}
              className={cn(
                "w-[300px] justify-start text-left font-normal",
                !date && "text-muted-foreground"
              )}
            >
              <CalendarIcon className="mr-2 h-4 w-4" />
              {date?.from ? (
                date.to ? (
                  <>
                    {format(date.from, "yyyy-MM-dd")} -{" "}
                    {format(date.to, "yyyy-MM-dd")}
                  </>
                ) : (
                  format(date.from, "yyyy-MM-dd")
                )
              ) : (
                <span>Pick a date</span>
              )}
            </Button>
        </PopoverTrigger>
        <PopoverContent className="w-auto p-0" align="start">
          <Calendar
            mode="range"
            defaultMonth={date?.from}
            selected={date}
            onSelect={setDateHook}
            numberOfMonths={2}
          />
        </PopoverContent>
      </Popover>
    </div>
  );
}

export default DatePickerWithRange;
